<template>
  <div class="container">
    <page-header 
      title="ETC卡充值记录" 
      subtitle="记录和管理所有车辆的ETC卡充值信息"
    >
      <template #actions>
        <el-button type="primary" @click="openDialog()" class="btn-with-icon">
          <el-icon class="mr-1"><Plus /></el-icon>添加充值记录
        </el-button>
        <el-button type="success" @click="exportData" class="btn-with-icon">
          <el-icon class="mr-1"><Download /></el-icon>导出数据
        </el-button>
      </template>
    </page-header>
    
    <el-card shadow="hover" class="mb-6 card-with-hover">
      <div class="search-container flex items-center flex-wrap gap-4">
        <el-input
          v-model="searchQuery"
          placeholder="搜索ETC卡号"
          prefix-icon="Search"
          clearable
          @clear="filterRecharges"
          @input="debounceSearch"
          style="width: 240px"
          class="search-input"
        />
        <div class="flex gap-2 ml-auto">
          <el-button type="primary" @click="filterRecharges" :loading="loading" class="search-btn">
            <el-icon class="mr-1"><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch" class="reset-btn">
            <el-icon class="mr-1"><Refresh /></el-icon>重置
          </el-button>
        </div>
      </div>
    </el-card>
    
    <el-card shadow="hover" class="overflow-hidden card-with-hover">
      <el-table
        v-loading="loading"
        :data="filteredRecharges"
        border
        stripe
        style="width: 100%"
        :header-cell-class-name="'bg-gray-100 dark:bg-gray-700'"
        class="custom-table"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="cardNumber" label="ETC卡号" width="180" />
        <el-table-column prop="rechargeTime" label="充值时间" width="180" />
        <el-table-column prop="amount" label="充值金额" width="120" align="right">
          <template #default="scope">
            {{ scope.row.amount.toFixed(2) }} 元
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120" />
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" effect="light" class="status-tag">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div class="flex gap-1">
              <el-button 
                type="primary" 
                size="small"
                @click="editRecharge(scope.row)"
                class="edit-btn"
              >
                <el-icon class="mr-1"><Edit /></el-icon>编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                @click="deleteRecharge(scope.row)"
                class="delete-btn"
              >
                <el-icon class="mr-1"><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container mt-4 flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="DEFAULT_PAGE_SIZES"
          :total="totalRecharges"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑充值记录对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑充值记录' : '添加充值记录'"
      width="500px"
      destroy-on-close
      class="custom-dialog"
    >
      <el-form
        ref="rechargeForm" 
        :model="rechargeForm" 
        :rules="rules" 
        label-width="100px"
        label-position="right"
        class="form-container"
      >
        <el-form-item label="ETC卡号" prop="cardNumber">
          <el-select 
            v-model="rechargeForm.cardNumber" 
            placeholder="请选择ETC卡" 
            filterable
            style="width: 100%"
          >
            <el-option 
              v-for="card in etcCards" 
              :key="card.id" 
              :label="card.cardNumber" 
              :value="card.cardNumber" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="充值时间" prop="rechargeTime">
          <el-date-picker
            v-model="rechargeForm.rechargeTime"
            type="datetime"
            placeholder="选择充值时间"
            format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input-number 
            v-model="rechargeForm.amount" 
            :precision="2" 
            :step="100" 
            :min="0" 
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select 
            v-model="rechargeForm.paymentMethod" 
            placeholder="请选择支付方式"
            style="width: 100%"
          >
            <el-option label="现金" value="现金" />
            <el-option label="微信" value="微信" />
            <el-option label="支付宝" value="支付宝" />
            <el-option label="银行转账" value="银行转账" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作人" prop="operator">
          <el-input v-model="rechargeForm.operator" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select 
            v-model="rechargeForm.status" 
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option label="成功" value="成功" />
            <el-option label="失败" value="失败" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="rechargeForm.remark" 
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRecharge" :loading="submitLoading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { Plus, Download, Search, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageHeader from '@/components/PageHeader.vue'
import { DEFAULT_PAGE_SIZES } from '@/utils/constants'

export default {
  name: 'EtcRechargeView',
  components: {
    PageHeader,
    Plus,
    Download,
    Search,
    Edit,
    Delete,
    Refresh
  },
  setup() {
    // 充值记录数据
    const recharges = ref([])
    const filteredRecharges = ref([])
    const searchQuery = ref('')
    const pageSize = ref(10)
    const currentPage = ref(1)
    const totalRecharges = ref(0)
    const loading = ref(false)
    const submitLoading = ref(false)
    
    // ETC卡选项
    const etcCards = ref([])
    
    // 对话框控制
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const editId = ref(null)
    
    // 表单数据和验证规则
    const rechargeForm = reactive({
      cardNumber: '',
      rechargeTime: new Date(),
      amount: 0,
      paymentMethod: '现金',
      operator: '',
      status: '成功',
      remark: ''
    })
    
    const rules = {
      cardNumber: [{ required: true, message: '请选择ETC卡', trigger: 'change' }],
      rechargeTime: [{ required: true, message: '请选择充值时间', trigger: 'change' }],
      amount: [{ required: true, message: '请输入充值金额', trigger: 'blur' }],
      paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
      operator: [{ required: true, message: '请输入操作人', trigger: 'blur' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    }
    
    // 加载充值记录数据
    const loadRecharges = () => {
      loading.value = true
      // 模拟API调用
      // 实际项目中应替换为真实API调用
      setTimeout(() => {
        const mockData = [
          {
            id: 1,
            cardNumber: 'ETC100120053004',
            rechargeTime: '2023-01-15 09:30:00',
            amount: 800.00,
            paymentMethod: '微信',
            operator: '张三',
            status: '成功',
            remark: '总经理车辆ETC卡充值'
          },
          {
            id: 2,
            cardNumber: 'ETC200130064005',
            rechargeTime: '2023-02-20 14:15:00',
            amount: 500.00,
            paymentMethod: '支付宝',
            operator: '李四',
            status: '成功',
            remark: '销售部ETC卡充值'
          },
          {
            id: 3,
            cardNumber: 'ETC300140075006',
            rechargeTime: '2023-03-05 11:00:00',
            amount: 600.00,
            paymentMethod: '银行转账',
            operator: '王五',
            status: '成功',
            remark: '技术部ETC卡充值'
          }
        ]
        
        recharges.value = mockData
        filteredRecharges.value = [...recharges.value]
        totalRecharges.value = mockData.length
        loading.value = false
      }, 500)
    }
    
    // 加载ETC卡数据
    const loadEtcCards = () => {
      // 模拟ETC卡数据
      etcCards.value = [
        { id: 1, cardNumber: 'ETC100120053004' },
        { id: 2, cardNumber: 'ETC200130064005' },
        { id: 3, cardNumber: 'ETC300140075006' },
        { id: 4, cardNumber: 'ETC400150086007' }
      ]
    }
    
    // 筛选充值记录
    const filterRecharges = () => {
      loading.value = true
      setTimeout(() => {
        if (!searchQuery.value) {
          filteredRecharges.value = [...recharges.value]
        } else {
          filteredRecharges.value = recharges.value.filter(recharge => 
            recharge.cardNumber.includes(searchQuery.value)
          )
        }
        totalRecharges.value = filteredRecharges.value.length
        loading.value = false
      }, 300)
    }
    
    // 防抖搜索
    let searchTimeout = null
    const debounceSearch = () => {
      if (searchTimeout) {
        clearTimeout(searchTimeout)
      }
      searchTimeout = setTimeout(() => {
        filterRecharges()
      }, 500)
    }
    
    // 重置搜索
    const resetSearch = () => {
      searchQuery.value = ''
      filterRecharges()
    }
    
    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      filterRecharges()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      filterRecharges()
    }
    
    // 打开对话框
    const openDialog = (recharge = null) => {
      if (recharge) {
        isEdit.value = true
        editId.value = recharge.id
        Object.keys(rechargeForm).forEach(key => {
          rechargeForm[key] = recharge[key]
        })
        if (typeof rechargeForm.rechargeTime === 'string') {
          rechargeForm.rechargeTime = new Date(rechargeForm.rechargeTime)
        }
      } else {
        isEdit.value = false
        editId.value = null
        // 重置表单
        rechargeForm.cardNumber = ''
        rechargeForm.rechargeTime = new Date()
        rechargeForm.amount = 0
        rechargeForm.paymentMethod = '现金'
        rechargeForm.operator = ''
        rechargeForm.status = '成功'
        rechargeForm.remark = ''
      }
      
      dialogVisible.value = true
      
      // 等待DOM更新后重置表单验证
      setTimeout(() => {
        if (document.querySelector('.el-form')) {
          document.querySelector('.el-form').resetFields && document.querySelector('.el-form').resetFields()
        }
      }, 0)
    }
    
    // 编辑充值记录
    const editRecharge = (row) => {
      openDialog(row)
    }
    
    // 删除充值记录
    const deleteRecharge = (row) => {
      ElMessageBox.confirm(
        `确定要删除卡号为 ${row.cardNumber} 的充值记录吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        loading.value = true
        try {
          // 模拟API调用删除操作
          await new Promise(resolve => setTimeout(resolve, 500))
          
          // 从数据中移除该记录
          recharges.value = recharges.value.filter(item => item.id !== row.id)
          filteredRecharges.value = filteredRecharges.value.filter(item => item.id !== row.id)
          totalRecharges.value = filteredRecharges.value.length
          
          ElMessage.success('删除成功')
        } catch (error) {
          ElMessage.error('删除失败')
          console.error('删除失败:', error)
        } finally {
          loading.value = false
        }
      }).catch(() => {
        // 用户取消删除
      })
    }
    
    // 保存充值记录
    const saveRecharge = async () => {
      // 在实际项目中应该使用表单引用
      // if (!rechargeFormRef.value) return
      
      submitLoading.value = true
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 800))
        
        if (isEdit.value) {
          // 更新现有记录
          const index = recharges.value.findIndex(item => item.id === editId.value)
          if (index !== -1) {
            recharges.value[index] = { ...recharges.value[index], ...rechargeForm, id: editId.value }
            ElMessage.success('编辑充值记录成功')
          }
        } else {
          // 添加新记录
          const newId = recharges.value.length > 0 ? Math.max(...recharges.value.map(item => item.id)) + 1 : 1
          recharges.value.push({
            id: newId,
            ...rechargeForm,
            rechargeTime: typeof rechargeForm.rechargeTime === 'object' 
              ? rechargeForm.rechargeTime.toLocaleString() 
              : rechargeForm.rechargeTime
          })
          ElMessage.success('添加充值记录成功')
        }
        
        // 更新过滤后的数据
        filterRecharges()
        dialogVisible.value = false
      } catch (error) {
        ElMessage.error(isEdit.value ? '编辑充值记录失败' : '添加充值记录失败')
        console.error('保存失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
    
    // 导出数据
    const exportData = () => {
      ElMessage({
        message: 'ETC卡充值记录导出成功，请在下载中心查看',
        type: 'success',
        duration: 2000
      })
      // 实际项目中应调用导出API
      // window.location.href = '/api/recharge/etc/export'
    }
    
    // 获取状态标签类型
    const getStatusType = (status) => {
      const types = {
        '成功': 'success',
        '失败': 'danger'
      }
      return types[status] || 'info'
    }
    
    // 初始化
    onMounted(() => {
      loadRecharges()
      loadEtcCards()
    })
    
    return {
      recharges,
      filteredRecharges,
      searchQuery,
      pageSize,
      currentPage,
      totalRecharges,
      loading,
      submitLoading,
      dialogVisible,
      isEdit,
      rechargeForm,
      etcCards,
      DEFAULT_PAGE_SIZES,
      loadRecharges,
      filterRecharges,
      debounceSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      openDialog,
      editRecharge,
      deleteRecharge,
      saveRecharge,
      exportData,
      getStatusType
    }
  }
}
</script>

<style scoped>
.el-table :deep(.el-table__header) th {
  font-weight: 600;
}

.el-card {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 8px;
}

.card-with-hover:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.status-tag {
  min-width: 70px;
  text-align: center;
  font-weight: 500;
  border-radius: 4px;
  transition: all 0.3s;
}

.btn-with-icon {
  display: flex;
  align-items: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.btn-with-icon:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
}

.custom-pagination {
  margin-top: 16px;
}

.custom-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  padding: 16px 20px;
}

.custom-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #eee;
  padding: 16px 20px;
}

.search-input {
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.search-input:focus {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 编辑和删除按钮样式 */
.edit-btn, .delete-btn {
  transition: all 0.3s;
}

.edit-btn:hover, .delete-btn:hover {
  transform: translateY(-2px);
}

.edit-btn:hover {
  background-color: var(--el-color-primary-light-3);
}

.delete-btn:hover {
  background-color: var(--el-color-danger-light-3);
}

/* 表格行样式 */
:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: var(--el-color-primary-light-9) !important;
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 修复暗黑模式下的表格样式 */
:deep(.dark-theme .el-table) {
  --el-table-border-color: var(--border-color);
  --el-table-header-bg-color: var(--bg-color);
}

/* 暗黑模式下的卡片悬浮效果 */
:deep(.dark-theme .card-with-hover:hover) {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
}
</style>